package cn.slipi.core.plugin.pre;

import cn.slipi.common.constants.Constants;
import cn.slipi.common.entity.PdrApi;
import cn.slipi.common.entity.RequestLog;
import cn.slipi.common.enums.PluginDetailEnum;
import cn.slipi.common.rule.custom.entity.MatchCondition;
import cn.slipi.core.cache.ApiManager;
import cn.slipi.core.plugin.AbstractPlugin;
import cn.slipi.core.plugin.IPluginChain;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * FireWallPlugin
 */
public class FireWallPlugin extends AbstractPlugin {

    private static final Logger LOGGER = LoggerFactory.getLogger(FireWallPlugin.class);

    private final ApiManager apiManager;

    public FireWallPlugin(final ApiManager apiManager) {
        super(apiManager);
        this.apiManager = apiManager;
    }


    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, IPluginChain chain) {
        RequestLog requestLog = (RequestLog) exchange.getAttributes().get(Constants.REQUEST_LOG);

        MatchCondition requestCondition = (MatchCondition) exchange.getAttributes().get(Constants.GATEWAY_HEADER);
        PdrApi pdrApi = this.apiManager.getApiByCode(requestCondition.getApiCode());
        String blackList = pdrApi.getBlackList();
        final List<String> blacks = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(blackList);
        InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
        String clientIp = Objects.requireNonNull(remoteAddress).getAddress().getHostAddress();
        if (StringUtils.isNotBlank(clientIp)) {
            Optional<String> first = blacks.stream()
                    .filter(b -> StringUtils.equals(clientIp, b))
                    .findFirst();
            if (first.isPresent()) {
                requestLog.setFireWall("forbidden");
                exchange.getAttributes().put(Constants.REQUEST_LOG, requestLog);
                return this.response(HttpStatus.FORBIDDEN);
            }
        }

        requestLog.setFireWall("ok");
        exchange.getAttributes().put(Constants.REQUEST_LOG, requestLog);
        return chain.execute(exchange);
    }

    @Override
    public String getPluginPhase() {
        return PluginDetailEnum.FIREWALL.getPhase();
    }

    @Override
    public int getCode() {
        return PluginDetailEnum.FIREWALL.getCode();
    }

    @Override
    public String getName() {
        return PluginDetailEnum.FIREWALL.getName();
    }
}
